package gov.pbc.nn.kjgl.item.project;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.business.IDept;
import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.core.Configure;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;
import com.bstek.dorado.uploader.DownloadFile;
import com.bstek.dorado.uploader.UploadFile;
import com.bstek.dorado.uploader.annotation.FileProvider;
import com.bstek.dorado.uploader.annotation.FileResolver;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.bdf.service.DeptService;
import gov.pbc.nn.core.utils.SecurityUtils;
import gov.pbc.nn.kjgl.Constants;
import gov.pbc.nn.kjgl.entity.Project;
import gov.pbc.nn.kjgl.entity.ProjectFile;
import gov.pbc.nn.kjgl.item.dao.ProjectItemDao;
import gov.pbc.nn.kjgl.item.entity.ProjectItem;
import gov.pbc.nn.kjgl.item.template.entity.AbstractItem;
import gov.pbc.nn.kjgl.item.template.service.AbstractItemService;

@Component("projectItemPR")
public class ProjectItemPR extends AbstractItemService {

	@Autowired
	private ProjectItemDao projectItemDao;

	@Override
	public void saveItem(AbstractItem item) throws Exception {
		ProjectItem ei = (ProjectItem) item;
		EntityState es = EntityUtils.getState(ei);
		if (es == EntityState.NEW) {
			// ei.setDeptId(ContextHolder.getLoginUser().getDepts().get(0).getId());
			// ei.setDeptName(ContextHolder.getLoginUser().getDepts().get(0).getName());
			this.projectItemDao.save(ei);
		} else {
			if (es == EntityState.MODIFIED) {
				this.projectItemDao.update(ei);
			}
		}
	}

	@DataProvider
	public ProjectItem getEmailItem(String id) throws Exception {

		ProjectItem projectItem = (ProjectItem) this.projectItemDao.get(id, ProjectItem.class);
//		ProjectItem projectNew = null;
		ProjectItem projectNew = EntityUtils.toEntity(projectItem);
		if (projectItem.getFuzeImg() != null) {
			EntityUtils.setValue(projectNew, "fuzeImage", new String(projectItem.getFuzeImg()));
		}
		if (projectItem.getShenbaoImg() != null) {
			EntityUtils.setValue(projectNew, "sbbmImage", new String(projectItem.getShenbaoImg()));
		}
		return projectNew;
		// } else {
		// return projectItem;
		// }
	}

	@DataProvider
	public void getProject(Page<Project> page, Criteria criteria) {
		this.projectItemDao.getPageAll(page, criteria);
	}

	@Expose
	public boolean ajaxCheckKj(String username) {
		return projectItemDao.ajaxCheckKj(username);
	}

	@Expose
	@Transactional
	public void saveImage(Map<String, Object> params) {
		String id = (String) params.get("id");
		String image = (String) params.get("image");
		int type = (int) params.get("type");
		ProjectItem projectItem = new ProjectItem();
		if (type == 0) {
			projectItem = (ProjectItem) this.projectItemDao.get(id, ProjectItem.class);
			projectItem.setFuzeImg(image.getBytes());
		} else if (type == 1) {
			projectItem = (ProjectItem) this.projectItemDao.get(id, ProjectItem.class);
			projectItem.setShenbaoImg(image.getBytes());
		}
		this.projectItemDao.update(projectItem);
	}

	//
	// @DataProvider
	// public List<IUser> getkezhangs() {
	// Dept dept = (Dept) ContextHolder.getLoginUser().getDepts().get(0);
	// List<IUser> users =
	// SecurityUtils.getUserByRoleForDeptWithChildren(dept.getCDept().getId(),
	// Constants.ROLE_KZ);
	// return users;
	// }

	@FileResolver
	@Transactional
	public String process2(UploadFile file, Map<String, Object> parameter) throws Exception {
		String name = (String) parameter.get("name");
		String id = (String) parameter.get("id");

		if (StringUtils.isEmpty(name)) {
			throw new Exception("文件上传名称为空");
		}
		String basePath = Configure.getString("SHIXIANGSHENPI_RUANJIAN_FILE_UPLOAD_PATH");
		if (StringUtils.isEmpty(basePath)) {
			throw new IllegalArgumentException("必须指定档案文件上传的基本地址");
		}
		String returnValue = "";
		try {
			Path path = Paths.get(basePath);
			if (!Files.isDirectory(path)) {
				path = Files.createDirectories(path);
			}
			// path = path.resolve(file.getFileName());
			path = path.resolve(UUID.randomUUID().toString());

			File destFile = Files.createFile(path).toFile();
			// 保存projectFile表格，type设置成5，5是外部实体的引用
			ProjectFile entity = new ProjectFile();
			entity.setPath(path.toString());
			entity.setFileName(file.getFileName());
			entity.setOwnerId(id);
			entity.setType(5);
			this.projectItemDao.save(entity);
			// 关联保存到对应的字段
			this.updateProjectItemAndPfile(entity.getId(), file.getFileName(), id);
			file.transferTo(destFile);
			returnValue = entity.getId();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return returnValue;
	}

	// 关联保存上传文件的id和name
	public void updateProjectItemAndPfile(String Fid, String fileName, String Pid) {
		ProjectItem projectItem = this.projectItemDao.get(Pid, ProjectItem.class);
		projectItem.setManageDeptOpinion(fileName);
		projectItem.setManageDeptOpinionFileId(Fid);
		this.projectItemDao.update(projectItem);
	}

	@Expose
	@Transactional
	public void deleteProjectItemAndPfile(String projectItemId, String fId) throws IOException {
		ProjectItem projectItem = this.projectItemDao.get(projectItemId, ProjectItem.class);
		projectItem.setManageDeptOpinion(null);
		projectItem.setManageDeptOpinionFileId(null);
		this.projectItemDao.update(projectItem);

		// 删除pfile文件
		ProjectFile projectFile = this.projectItemDao.get(fId, ProjectFile.class);
		this.projectItemDao.delete(projectFile);
		// 删除磁盘中的文件
		this.projectItemDao.deleteProjectFile(projectFile);
	}

	@FileProvider
	public DownloadFile download(Map<String, String> parameter) throws IOException {
		ProjectFile pfile = projectItemDao.get(parameter.get("id").toString(), ProjectFile.class);
		String fileName = pfile.getFileName();
		String path = pfile.getPath();
		InputStream stream = new FileInputStream(path);
		DownloadFile file = new DownloadFile(fileName, stream);
		return file;
	}

	@Expose
	@Transactional
	public void saveOpinioin(String id, String opinion) {
		ProjectItem projectItem = this.projectItemDao.get(id, ProjectItem.class);
		projectItem.setFuzeUser(opinion);
		this.projectItemDao.update(projectItem);
	}
}
